#include "imapparsethread.h"
#include "../../../11-util/02-log_manager/logmanager.h"

static Logger * imapLogger = LogManager::getMissionLogger("__imap");
ImapParseThread::ImapParseThread(QObject *parent) {

}

/**
 * 如果socket断网,或者有一个命令出错,应该放弃整个队列.
 * TODO: 在执行一个任务时,如何关联一个函数,让外界/ui,显示一下更新,表明当前执行的进度?
 * TODO2: 如何写一个程序,向微信里发送一个消息?
 * @brief ImapParseThread::run
 */
void ImapParseThread::run()  {
    while(1){
        if(taskQueue.length() == 0) {
            QThread::sleep(1);
            continue;
        }
        ImapTask * task = taskQueue.dequeue();
        this->executeTask(task);
    }
}

/**
 * 将任务加入到队列等待执行.
 * @brief ImapParseThread::addTask
 * @param task
 */
void ImapParseThread::addTask(ImapTask * task) {
    taskQueue.enqueue(task);
}

void ImapParseThread::executeTask(ImapTask * task) {
    switch(task->type) {
    case ImapTaskType::Connect:{
        //连接任务
         QString fmt = "thread(%1) parse rawres";
        imapLogger->debug("ImapParseThread","ParseRaw","Before",fmt.arg(QString::number((long long)QThread::currentThreadId())));
        QString res = task->rawResult;
        task->result = res;
        // task->handler(res,res);
        //通知主线程更新数据.
         imapLogger->debug("ImapParseThread","ParseRaw","after",res);
        emit connectFinish(res);
        break;
    }
    default:{
        //非连接任务
        QString raw = task->rawResult;
        task->result = raw;
        imapLogger->debug("ImapParseThread","ParseRaw","after",raw);
        //回调函数机制不能跨线程,只能使用触发事件的槽函数.
        //socket超时,task执行失败.
        emit sendEvent(task->type,raw,raw);
        break;
    }
    }
}

QString ImapParseThread::readSocketSync() {
    // -1 代表等待无限.
    QString ret = "";
    if(mSocket->waitForReadyRead(30000)) {
        QByteArray buffer = this->mSocket->readAll();
        ret = "" + buffer;
        QString fmt("[S] [receive res:%1]");
        QString info = fmt.arg(ret);
        qDebug() << info;
    }
    return ret;
}

